<!--
 * @Description: 订单房间
 * 
 * @Author: XiongYaoYuan<xiongyaoyuan>
 * @Date: 2023-04-12 20:55:53
 * @FilePath: /yuxiuproweb/src/views/mes/pro/workorder/mods/room/index.vue
-->
<template>
  <el-drawer
    title="订单房间"
    size="100%"
    :visible.sync="shows"
    :before-close="handleClose"
  >
    <div class="app-container drawer-form" v-if="info">
      <el-descriptions :column="4" class="mb20">
        <el-descriptions-item label="订单编号">{{
          info.proOrderId
        }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">
          <div
            @click="
              edit = {
                show: true,
                data: {
                  ...info,
                },
              }
            "
          >
            <el-link type="primary">
              <i class="el-icon-edit"></i> {{ info.clientName }}
            </el-link>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="品牌">{{
          info.brandName
        }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{
          info.tel
        }}</el-descriptions-item>
        <el-descriptions-item label="下单时间">{{
          parseTime(info.createDate, "{y}-{m}-{d}")
        }}</el-descriptions-item>
        <el-descriptions-item label="交单时间">{{
          parseTime(info.submitTime, "{y}-{m}-{d}")
        }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <div class="advance">
            <el-tag size="small">{{
              getTypeName(dict.type.pro_order_state, info.state)
            }}</el-tag>
            <div class="advance-btn">
              <div
                :class="['btn1', { btn2: ![1, 2].includes(active) }]"
                @click="[1, 2].includes(active) ? submitForm(active - 1) : ''"
              >
                <img src="@/assets/images/arrow1.png" alt="" />
              </div>
              <div
                :class="['btn1', { btn2: active === 4 }]"
                @click="active !== 4 ? submitForm(active + 1) : ''"
              >
                <img src="@/assets/images/arrow2.png" alt="" />
              </div>
            </div>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="地址">{{
          info.address
        }}</el-descriptions-item>
        <el-descriptions-item label="备注">
          <div
            @click="
              remark = {
                show: true,
                data: {
                  ...info,
                },
              }
            "
          >
            <el-link type="primary">
              <i class="el-icon-edit"></i> {{ info.remark || "空" }}
            </el-link>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="操作">
          <el-button
            type="success"
            plain
            size="mini"
            icon="el-icon-document-checked"
            class="ml10"
            v-if="info.state !== '3'"
            @click.stop="handleAddBatch()"
          >
            一键保存
          </el-button>
          <el-button
            type="warning"
            plain
            size="mini"
            icon="el-icon-document-copy"
            class="ml10"
            @click.stop="handleAddCopy()"
          >
            复制订单
          </el-button>
          <el-button
            type="primary"
            plain
            size="mini"
            icon="el-icon-circle-check"
            class="ml10"
            @click.stop="handleSplit()"
          >
            返单
          </el-button>
          <el-button
            size="mini"
            plain
            type="danger"
            icon="el-icon-delete"
            @click="handleRemove"
            >删除</el-button
          >
					<el-button
					  size="mini"
					  plain
					  type="danger"
					  icon="el-icon-delete"
					  @click="sumbitordermoney"
					  >提交财务审核变更单</el-button
					>
        </el-descriptions-item>
      </el-descriptions>
      <el-collapse v-model="activeNames">
        <!-- <pro-room-view
          :data="data"
          @active="(e) => (activeNames = e)"
        ></pro-room-view> -->
        <serve-view
          v-if="info.state === '3'"
          :list="proOrderList"
          @active="handleActive"
        ></serve-view>
        <curtain-view
          :data="info"
          ref="curtain"
          @active="handleActive"
          @on-submit="handleSubmit"
          @on-refresh-price="handleRefreshPrice"
        ></curtain-view>
        <decorate-view
          :data="info"
          ref="decorate"
          @on-submit="handleSubmit"
          @active="handleActive"
          @on-refresh-price="handleRefreshPrice"
        ></decorate-view>
        <other-view
          :data="info"
          ref="other"
          @on-submit="handleSubmit"
          @active="handleActive"
          @on-refresh-price="handleRefreshPrice"
        ></other-view>
        <raw-view
          :data="info"
          ref="raw"
          @on-submit="handleSubmit"
          @active="handleActive"
          @on-refresh-price="handleRefreshPrice"
        ></raw-view>
        <delivery-view
          :data="info"
          ref="delivery"
          @active="handleActive"
          @on-refresh-price="handleRefreshPrice"
        ></delivery-view>
        <summary-view
          :data="info"
          @active="handleActive"
          ref="summary"
        ></summary-view>
      </el-collapse>
    </div>
    <!-- <h2 class="ml20" style="color: red">总价：{{ data.totalPrice }}</h2> -->

    <!-- 修改客户名称 -->
    <edit-name-view
      v-if="edit.show"
      :show.sync="edit.show"
      v-bind="edit"
      @on-change="getOrderData"
    ></edit-name-view>
    <!-- 修改备注 -->
    <edit-remark-view
      v-if="remark.show"
      :show.sync="remark.show"
      v-bind="remark"
      @on-change="getOrderData"
    ></edit-remark-view>
    <!-- 推进 -->
    <advance-view
      v-if="advance.show"
      :show.sync="advance.show"
      v-bind="advance"
      @update="getOrderData()"
    ></advance-view>
    <!-- 复制订单 -->
    <copy-client-view
      v-if="copy.show"
      :show.sync="copy.show"
      v-bind="copy"
      @on-change="handleCopyChange"
    ></copy-client-view>
  </el-drawer>
</template>

<script>
import ServeView from "./serve";
import CurtainView from "./curtain";
import ProRoomView from "./proRoom";
import DecorateView from "./decorate";
import OtherView from "./other";
import RawView from "./raw";
import DeliveryView from "./delivery";
import SummaryView from "./summary";
import EditNameView from "../add/editName.vue";
import EditRemarkView from "../add/editRemark.vue";
import AdvanceView from "../../advance";
import CopyClientView from "../../copyClient";
import {
  getOrder,
  listProOrder,
  addProOrder,
  updateProOrder,
  auditOrder,
  delOrder,
  changeOrder,
} from "@/api/asc/order";

export default {
  dicts: ["pro_order_state"],
  components: {
    CurtainView,
    ProRoomView,
    DecorateView,
    OtherView,
    RawView,
    DeliveryView,
    SummaryView,
    EditNameView,
    AdvanceView,
    EditRemarkView,
    ServeView,
    CopyClientView,
  },
  props: {
    show: Boolean,
    type: {
      type: String,
      default: "add",
    },
    data: {
      type: Object,
    },
  },
  data() {
    return {
      activeNames: ["1", "5"],
      edit: {
        show: false,
        data: null,
      },
      remark: {
        show: false,
        data: null,
      },
      info: null,
      advance: {
        show: false,
        data: null,
      },
      copy: {
        show: false,
        data: null,
      },
      active: 0, // 当前订单状态
      proOrderList: [],
    };
  },
  computed: {
    shows: {
      get() {
        return this.show;
      },
      set(newValue) {
        this.$emit("update:show", newValue);
        if (!newValue) {
          this.$emit("update");
        }
      },
    },
  },
  async created() {
    this.getOrderData();
    await this.listProOrder();
    if (this.proOrderList?.length) {
      this.activeNames.push("0");
    }
  },
  methods: {
    handleClose(done) {
      this.$confirm("是否确定关闭？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          done();
        })
        .catch(() => {});
    },
    // 获取数据
    async getOrderData() {
      const { data } = await getOrder(this.data.proOrderId);
      this.info = data;
      this.active = +data.state || 0;
    },
    // 获取变更单
    async listProOrder() {
      const { rows } = await listProOrder({
        orderId: this.data.proOrderId,
        // state: "0",
      });
      this.proOrderList = rows;
    },
    /** 保存按钮 */
    async submitForm(state) {
      try {
        auditOrder({
          orderId: this.info.proOrderId,
          state,
        }).then(() => {
          this.$modal.msgSuccess("操作成功");
          this.getOrderData();
        });
      } catch (e) {
        console.log(e);
      }
    },
    handleActive(active, state) {
      if (!this.activeNames.includes(active)) {
        this.activeNames.push(active);
      } else {
        if (state === "1") {
          this.activeNames.splice(
            this.activeNames.findIndex((e) => e === active),
            1
          );
        }
      }
    },
    // 保存刷新总价
    handleRefreshPrice() {
      this.$nextTick(() => {
        this.$refs?.summary?.getMethod();
      });
    },
    // 删除
    handleRemove() {
      this.$modal
        .confirm(
          '是否确认删除订单编号为"' + this.data.proOrderId + '"的数据项？'
        )
        .then(() => {
          return delOrder(this.data.proOrderId);
        })
        .then(() => {
          this.$modal.msgSuccess("删除成功");
          this.shows = false;
        })
        .catch(() => {});
    },
    //提交财务审核变更单
	sumbitordermoney(){
		this.$modal
		  .confirm(
		    '是否确认提交订单编号为"' + this.data.proOrderId + '"的数据项？'
		  )
		  .then(() => {
		    return changeOrder(this.data.proOrderId);
		  })
		  .then(() => {
		    this.$modal.msgSuccess("提交成功");
		    this.shows = false;
		  })
		  .catch(() => {});
	},
	// 一键保存
    handleAddBatch() {
      try {
        this.$refs?.curtain.handleAddBatch();
        this.$refs?.decorate.handleAddBatch();
        this.$refs?.other.handleAddBatch();
        this.$refs?.raw.handleAddBatch();
        this.$refs?.delivery.handleSave();
        this.$refs?.summary.handleSave();
      } catch (e) {
        console.log(e);
      }
    },
    // 复制订单
    handleAddCopy() {
      this.copy = {
        show: true,
        data: this.info,
      };
    },
    // 复制订单回调
    handleCopyChange(data) {
      this.shows = false;
      this.$emit("on-copy-change", data);
    },
    // 返单
    handleSplit() {
      this.$emit("on-split", this.info);
    },
    // 保存变更单
    handleSubmit(rows, type, cell, remark, state) {
      console.log(item);
      // console.log(type);
      // console.log(this.proOrderList);
      // const item = this.proOrderList.find(
      //   (e) => e.orderId === this.data.proOrderId
      // );
      // console.log(item);

      const item = undefined;
      const customCurtain = item ? JSON.parse(item.customCurtain) : [];
      const customWindowCurtain = item
        ? JSON.parse(item.customWindowCurtain)
        : [];
      const customOther = item ? JSON.parse(item.customOther) : [];
      const raw = item ? JSON.parse(item.raw) : [];
      const params = {
        customCurtain: JSON.stringify(
          type === "0" ? [...customCurtain, ...rows] : customCurtain
        ),
        customWindowCurtain: JSON.stringify(
          type === "1" ? [...customWindowCurtain, ...rows] : customWindowCurtain
        ),
        customOther: JSON.stringify(
          type === "2" ? [...customOther, ...rows] : customOther
        ),
        raw: JSON.stringify(type === "3" ? [...raw, ...rows] : raw),

        customCurtainIds: type === "0" ? cell.proOrderCustomCurtainId : "",
        customWindowCurtainIds:
          type === "1" ? cell.orderCustomWindowCurtainId : "",
        customOtherIds: type === "2" ? cell.orderCustomOtherId : "",
        rawIds: type === "3" ? cell.orderRawId : "",
        content: remark,

        state: "0",
        type: state,
        orderId: this.data.proOrderId,
        clientName: this.info.clientName,
        variationOrderId: item?.variationOrderId || "",
      };
      // if (params.variationOrderId) {
      //   updateProOrder(params).then((res) => {
      //     console.log(res);
      //     this.listProOrder();
      //   });
      // } else {
      addProOrder(params).then(async (res) => {
        await this.listProOrder();
        if (this.proOrderList?.length) {
          !this.activeNames?.includes("0") && this.activeNames.push("0");
        }
      });
      // }
    },
  },
};
</script>

<style lang="scss" scoped>
.drawer-form {
  ::v-deep {
    .el-form-item {
      margin-bottom: 0;
      margin-right: 0;
      input {
        text-align: left;
      }
    }
    .el-collapse-item__header {
      height: 65px;
      line-height: 65px;
      font-size: 16px;
      color: #000;
      // & > i {
      //   display: none;
      // }
    }
  }
}
.advance {
  display: flex;
  align-items: center;
  .advance-btn {
    display: flex;
    align-items: center;
    .btn1 {
      width: 30px;
      height: 30px;
      background-color: #46a6ff;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-left: 10px;
      cursor: pointer;
      img {
        width: 20px;
        height: 20px;
      }
    }
    .btn2 {
      background-color: rgba($color: #000000, $alpha: 0.5);
      cursor: not-allowed;
    }
  }
}
</style>
